﻿#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void ready(char arr1[][11], char arr2[][11])
{
	int i = 0, j = 0;
	for (i = 0; i < 11; i++)
	{
		for (j = 0; j < 11; j++)
		{
			arr1[i][j] = '#';
			arr2[i][j] = '#';
		}
	}
	return;
}

void zhadan(char arr2[][11])
{
	int n = 10;
	while (n)
	{
		int h = rand() % 9;
		int l = rand() % 9;
		if (arr2[h + 1][l + 1] == '#')
		{
			arr2[h + 1][l + 1] = '*';
			n--;
		}
	}
	return;
}

void print(char arr[][11])
{
	int i = 0, j = 0;
	for (j = 0; j < 10; j++)
	{
		printf("%d  ", j);
	}
	printf("\n");
	for (i = 1; i < 10; i++)
	{
		printf("%d  ", i);
		for (j = 1; j < 10; j++)
		{
			printf("%c  ", arr[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}

void scan(char arr1[][11], char arr2[][11])
{
	printf("请输入排雷的坐标，以左上角为(1 1)：");
	int hang = 0, lie = 0;
	scanf("%d %d", &hang, &lie);
	int win = 0; //找到非雷的个数
	while (win < 71)
	{
		while (arr1[hang][lie] != '#' || hang < 1 || hang>9 || lie < 1 || lie>9)
		{
			printf("请输入正确的坐标，以左上角为(1 1)：");
			scanf("%d %d", &hang, &lie);
		}
		if (arr2[hang][lie] == '*')
		{
			printf("踩中炸弹，您输了。\n");
			printf("雷图：\n");
			print(arr2);
			return;
		}
		else
		{
			int count = getnumber(arr2, hang, lie);
			arr1[hang][lie] = '0' + count;
			win++;
			print(arr1);
		}
	}
	if (win == 71)
	{
		printf("排雷成功，您赢了");
		printf("雷图：\n");
		print(arr2);
	}
	return;
}

int getnumber(char arr[][11], int hang, int lie)
{
	int i = 0, j = 0;
	int sum = 0;
	for (i = hang - 1; i <= hang + 1; i++)
	{
		for (j = lie - 1; j <= lie + 1; j++)
		{
			sum += arr[i][j];
		}
	}
	sum = (sum - '#' * 9) / 7;
	return sum;
}

int main()
{
	srand((unsigned)time(NULL));
	int n = 0;
	printf("扫雷\n");  //游戏介绍+菜单打印
	printf("游戏简介：游戏目标是在最短的时间内根据点击格子出现的数字找出所有非雷格子，同时避免踩雷，踩到一个雷即全盘皆输。\n");
	printf("输入1开始游戏，输入0退出游戏：");
	scanf("%d", &n);
	while (n)
	{
		if (n == 1)  //进入游戏
		{
			char arr1[11][11] = { 0 };  //展现给用户
			char arr2[11][11] = { 0 };  //后台答案
			ready(arr1, arr2);  //初始化棋盘
			zhadan(arr2);  //布置10炸弹
			print(arr1);   //打印棋盘
			//print(arr2); //test炸弹是否正常放置
			scan(arr1, arr2);
			printf("游戏结束，请选择（1再来一把，0退出游戏）：");
			scanf("%d", &n);
		}
		else  //数字不合法，重新输入
		{
			printf("输入数字不合法，请重新选择（1开始游戏，0退出游戏）：");
			scanf("%d", &n);
		}
	}
	printf("游戏已退出，感谢游玩！");
	return 0;
}